<template>
  <base-breadcrumb :title="titleName">
    <a-row
      :gutter="10"
      class="page-height"
    >
      <!-- 树搜索 -->
      <a-col
        :span="6"
        class="permission-collapsed"
        :class="{ 'permission-tree-collapsed': collapsed }"
      >
        <a-card
          :style="{ border: collapsed ? 'none' : 'border: 1px solid #e8e8e8' }"
          class="page-height-tree"
        >
          <title-name title="组织架构" />
          <PermissionTreeOrganization
            :collapsed.sync="collapsed"
            @select="handleSelect"
          />
        </a-card>
      </a-col>
      <!-- 树搜索 -->
      <a-col
        :span="18"
        class="permission-collapsed page-height-list-wrapper"
        :style="collapsed ? 'width:calc(100% - 10px)' : ''"
      >
        <searchData
          ref="searchData"
          :search-data="searchArr"
          @search="search"
        />

        <a-card
          :bordered="false"
          class="page-height-list"
        >
          <!-- <title-name title="施工日志列表" /> -->
          <a-button
            v-btnPermission="[{code:'seex_pm_028_exp_04',ident:'prma_seex'},{code:'buco_pm_028_exp_04',ident:'prma_buco'}]"
            class="mb12"
            type="primary"
            :loading="batchLoading"
            @click="handlExport"
          >
            批量导出
          </a-button>
          <BasePrintButton
            ref="BasePrintButton"
            v-btnPermission="[{code:'seex_pm_028_pri_05',ident:'prma_seex'},{code:'buco_pm_028_pri_05',ident:'prma_buco'}]"
            type="primary"
            :before-print-fn="handlPrint"
            :button-text="'批量打印'"
            class="ml12"
            style="display: inline-block"
          />
          <div class="pub-table-select-count">
            <a-icon
              type="info-circle"
              theme="twoTone"
            />
            <span style="margin-right: 12px">
              施工日志总数：<span class="totalNum">{{ totalDels.constructionLogCount || 0 }} 个 </span>| 待填写：<span class="totalNum">{{ totalDels.toFillIn || 0 }} 个 </span>| 已填写：<span
                class="totalNum">{{ totalDels.filled || 0 }} 个 </span>| 核查完成：<span class="totalNum">{{ totalDels.checked || 0 }} 个
              </span>
            </span>
          </div>

          <list-table
            ref="table"
            bordered
            size="default"
            row-key="id"
            :columns="columns"
            :request="loadData"
            :alert="true"
            show-size-changer
            show-quick-jumper
            show-pagination="auto"
          >
            <span
              slot="serial"
              slot-scope="text, record, index"
            >{{ index + 1 }}</span>
            <span
              slot="action"
              slot-scope="text, record"
            >
              <MoreButton>
                  <a
                    v-btnPermission="[{code:'seex_pm_028_loo_01',ident:'prma_seex'},{code:'buco_pm_028_loo_01',ident:'prma_buco'}]"
                    @click="handleDels(record)"
                  >查看</a>
                <template v-if="record.isRetractButton === 1">
                  <a @click="handleWithdraw(record)">撤回</a>
                </template>
                <template v-if="record.statusCode == 1">
                    <a
                    v-btnPermission="[{code:'seex_pm_028_wri_02',ident:'prma_seex'},{code:'buco_pm_028_wri_02',ident:'prma_buco'}]"
                    @click="handleFill(record)"
                  >填写</a>
                </template>
                <template v-if="record.isCheckButton == 1">
                 <a
                    v-btnPermission="[{code:'seex_pm_028_ins_02',ident:'prma_seex'},{code:'buco_pm_028_ins_02',ident:'prma_buco'}]"
                    @click="handleCheck(record)"
                  >核查</a>
                </template>
              </MoreButton>
            </span>
          </list-table>
        </a-card>
      </a-col>
    </a-row>
  </base-breadcrumb>
</template>

<script>
import { getLogList, getLogTotal, retract, docExportBatc, docPrintBatch } from '@/api/project/constructionLog'
import PermissionTreeOrganization from '@/components/businessComponents/PermissionTreeOrganization'
import { planProducer } from '@/api/config'
import { downloadPost } from '@/utils/request2'

const searchArr = [
  // 搜索框
  {
    name: '项目名称',
    value: 'projectName',
    type: 'input'
  },
  {
    name: '项目编号',
    value: 'projectNum',
    type: 'input'
  },
  // {
  //   name: '分公司',
  //   valueKey: 'branchCompanyId',
  //   type: SelectSubCompany
  // },
  {
    name: '日志时间',
    value: 'times',
    type: 'dateRange'
  },
  {
    name: '状态',
    value: 'statusCode',
    type: 'select',
    data: [
      {
        value: '1',
        label: '待填写'
      },
      {
        value: '2',
        label: '已填写'
      },
      {
        value: '3',
        label: '核查完成'
      }
    ]
  }
]

const columns = [
  {
    title: '序号',
    width: 65,
    scopedSlots: { customRender: 'serial' }
  },
  {
    title: '日志编号',
    dataIndex: 'logNum',
    width: 180
  },
  {
    title: '项目名称',
    width: '20%',
    dataIndex: 'projectName',
    width: 220
  },
  {
    title: '项目编号',
    dataIndex: 'projectNum',
    width: 140
  },
  {
    title: '分公司',
    dataIndex: 'branchCompanyName',
    width: 140
  },
  {
    title: '日志日期',
    dataIndex: 'logDate',
    width: 140
  },
  {
    title: '核查日期',
    dataIndex: 'checkDate',
    width: 140
  },
  {
    title: '状态',
    dataIndex: 'statusName',
    width: 140
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 160,
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  name: 'a' + Date.now(),
  components: {
    PermissionTreeOrganization
  },
  data() {
    this.columns = columns
    return {
      searchArr,
      titleName: '',
      select: null, //组织架构选中项
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      loginCode: null,
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        // if (!this.select) {
        //   return
        // }
        const requestParameters = Object.assign({}, parameter, {
          branchComId: this.select?.orgId,
          projectId: this.select?.projectId,
          ...this.queryParam
        })
        return getLogList(requestParameters).then((res) => {
          return res
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      totalDels: {},
      // 收缩展开树
      collapsed: false,
      // 批量导出打印loading
      batchLoading: false
    }
  },

  created() {
    this.getLogTotal()
    let postss = JSON.parse(sessionStorage.getItem('ycloud-user_info')).employee.posts

    this.loginCode = postss.some(function (item) {
      if (item.code == 'PDLXMJL') {
        return true
      }
    })
  },
  computed: {
    // rowSelection() {
    //   return {
    //     selectedRowKeys: this.selectedRowKeys,
    //     selectedRows: this.selectedRows,   // 当前行所有数据
    //     onChange: this.onSelectChange
    //   }
    // }
  },
  methods: {
    /**
     * @description: 树选中
     * @param {object} node 节点对象
     * @return {void}
     */
    handleSelect(node) {
      this.select = node
      this.search()
    },
    handleDels(val) {
      // 查看
      this.$router.push({ path: '/project/constructionLog/details', query: { isCheck: 0, logId: val.id } })
    },

    handleFill(val) {
      // 填写
      this.$router.push({ path: '/project/constructionLog/edit', query: { logId: val.id } })
    },

    handleCheck(val) {
      // 核查
      this.$router.push({ path: '/project/constructionLog/verification', query: { isCheck: 1, logId: val.id } })
    },

    search(val) {
      if (val) {
        this.queryParam = val
      }
      // if (this.queryParam.logDateStart ) {
      //   this.queryParam.logDateStart = (this.queryParam.logDateStart[0]).format('YYYY-MM-DD')
      //   this.queryParam.logDateEnd = (this.queryParam.logDateEnd[1]).format('YYYY-MM-DD')
      // }
      if (this.queryParam.times && this.queryParam.times.length !== 0) {
        this.queryParam.logDateStart = this.formatDate(this.queryParam.times[0])
        this.queryParam.logDateEnd = this.formatDate(this.queryParam.times[1])
      }

      this.$refs.table.refresh(true)
      this.getLogTotal()
    },

    getLogTotal() {
      getLogTotal({ branchComId: this.select?.orgId, projectId: this.select?.projectId, ...this.queryParam }).then((res) => {
        this.totalDels = res.data
      })
    },

    handleEdit(val) {
      this.$router.push({
        path: '/project/constructionLog/edit',
        query: { logId: val.id, months: val.assessmentTime, name: val.subcontractorName }
      })
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    /**
     * @description: 批量导出
     * @return {void}
     */
    async handlExport() {
      try {
        this.batchLoading = true
        this.$refs.BasePrintButton.loadingState.isPrint = true
        const params = { branchComId: this.select?.orgId, projectId: this.select?.projectId, ...this.$refs.searchData.form.getFieldsValue() }
        if (params.times) {
          params.logDateStart = params.times[0].format('YYYY-MM-DD')
          params.logDateEnd = params.times[1].format('YYYY-MM-DD')
        }
        await downloadPost(planProducer + '/construction/log/doc-export-batch', params, undefined, '施工日志列表批量导出.zip')
      } catch (error) {
        console.log(error)
      } finally {
        this.batchLoading = false
        this.$refs.BasePrintButton.loadingState.isPrint = false
      }
    },
    /**
     * @description: 批量打印
     * @return {void}
     */
    async handlPrint() {
      try {
        this.batchLoading = true
        this.$refs.BasePrintButton.loadingState.isPrint = true
        const params = { branchComId: this.select?.orgId, projectId: this.select?.projectId, ...this.$refs.searchData.form.getFieldsValue() }
        if (params.times) {
          params.logDateStart = params.times[0].format('YYYY-MM-DD')
          params.logDateEnd = params.times[1].format('YYYY-MM-DD')
        }
        const res = await docPrintBatch(params)
        return res.data.content
      } catch (error) {
        console.log(error)
        this.$warning('打印失败')
        return Promise.reject(error)
      } finally {
        this.batchLoading = false
      }
    },
    /**
     * @description: 撤回
     * @param {object} record 行数据
     * @return {void}
     */
    handleWithdraw(record) {
      const vm = this
      this.$confirm({
        content: '请确认是否要撤回本人已填写的日志，撤回后需重新提交',
        onOk: () => {
          return new Promise((resolve, reject) => {
            retract({
              id: record.id
            }).then(({ code }) => {
              if (code === 200) {
                vm.$message.success('撤回成功')
                this.$refs.table.refresh()
                resolve()
              } else {
                vm.$message.warning('撤回失败')
                reject()
              }
            })
          })
        }
      })
    }
  }
}
</script>



